import React, { useEffect, useState } from 'react';
import ArrowRightIcon from '@mui/icons-material/ArrowRight';
import './index.less';
import img from '@/assets/images/home/xiaolang.png';
import examination from '@/assets/images/home/examination.png';
import books from '@/assets/images/home/books.png';
import practice from '@/assets/images/home/practice.png';
import { HomeApi } from '@/api';
import Subjects from '@/components/subjects';
import { useNavigate } from 'react-router-dom';
import useToast from '@/utils/toast';
interface IHomeDataModel {
  tit: string;
  collect: number;
  study: number;
  wrong: number;
  total: number;
  subjects: IHomeDataCon[];
  subjectCode: string;
}
// 定义一个自定义hoot
function useHomeData(): [IHomeDataModel, () => void] {
  const [tit, setTit] = useState('');
  const [collect, setCollect] = useState(0);
  const [study, setStudy] = useState(0);
  const [wrong, setWrong] = useState(0);
  const [total, setTotal] = useState(0);
  const [subjects, setSubjects] = useState<IHomeDataCon[]>([]);
  const [subjectCode, setSubjectCode] = useState('');
  // useState 可以传递泛型，用来约定前面的数据的类型
  const SetHomeData = () => {
    // 首页的数据，可能在长时间内，是不需要重新发请求的，为了优化性能，如果需要获取数据，先判断缓存里面有没有，有则直接从缓存中获取，如果没有再发请求
    // 注意：做切换学科的功能，在点击切换的时候，需要把缓存清掉，因为两边的数据不一样
    let homeData = sessionStorage.getItem('homedata');
    if (homeData) {
      // 如果存在，则在sessionstorage里面取
      const data = JSON.parse(homeData) as IHomeData;
      setTit(data.exam.title);
      setCollect(data.collect);
      setStudy(data.study);
      setWrong(data.wrong);
      setTotal(data.exam.itemCount);
      setSubjects(data.exemItems);
      setSubjectCode(data.exam.actionCode);
    } else {
      // 没有数据，向服务器发送方请求
      HomeApi().then((res) => {
        if (res.errCode === 0) {
          // console.log(res);
          setTit(res.data.exam.title);
          setCollect(res.data.collect);
          setStudy(res.data.study);
          setWrong(res.data.wrong);
          setTotal(res.data.exam.itemCount);
          setSubjects(res.data.exemItems);
          setSubjectCode(res.data.exam.actionCode);
          // 请求回来的数据存储到sessionstorage里面
          sessionStorage.setItem('homedata', JSON.stringify(res.data));
        }
      });
    }
  };
  useEffect(() => {
    SetHomeData();
  }, []);
  const HomeData: IHomeDataModel = {
    tit,
    collect,
    study,
    wrong,
    total,
    subjectCode,
    subjects,
  };
  return [HomeData, SetHomeData];
}
export default function Home() {
  const [HomeData, SetHomeData] = useHomeData();
  const navigate = useNavigate();
  let toast = useToast();
  return (
    <div className="home">
      <div className="top">
        <div className="tit">{HomeData.tit}</div>
        <div
          className="top_r"
          onClick={() =>
            navigate(`/select`, {
              state: {
                actionCode: HomeData.subjectCode,
                title: HomeData.tit,
              },
            })
          }
        >
          <span>切换考试科目</span>
          <ArrowRightIcon />
        </div>
      </div>
      <section className="banner">
        <p>欢迎使用IT猿题库！</p>
        <section className="banner_content">
          <img src={img} alt="" />
          <div className="banner_content_r">
            <div className="study">
              <span>已学{HomeData.study}题</span>
              <span className="division">|</span>
              <span>共{HomeData.total}题</span>
            </div>
            <ul className="err">
              <li className="err_item">
                <span className="num">{HomeData.wrong}</span>
                <span>错题</span>
              </li>
              <li className="err_item">
                <span className="num">{HomeData.collect}</span>
                <span>收藏</span>
              </li>
            </ul>
          </div>
        </section>
      </section>
      <section className="nav">
        <ul className="nav_concent">
          <li
            className="nav_item"
            onClick={() => toast('warning', '该功能暂未开放')}
          >
            <img src={examination} alt="" />
          </li>
          <li
            className="nav_item"
            onClick={() => toast('warning', '该功能暂未开放')}
          >
            <img src={books} alt="" />
          </li>
          <li
            className="nav_item"
            onClick={() => toast('warning', '该功能暂未开放')}
          >
            <img src={practice} alt="" />
          </li>
        </ul>
      </section>
      <section className="subject">
        <div className="tit">
          <p>学科题库</p>
          <span>坚持每一天，成长看得见</span>
        </div>
        {HomeData.subjects.map((item) => (
          <Subjects key={item.id} data={item}></Subjects>
        ))}
      </section>
    </div>
  );
}
